<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-select v-model="queryParams.title" placeholder="请选择标题" clearable>
          <el-option
            v-for="dict in dict.type.banner_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select v-model="queryParams.state" placeholder="请选择">
          <el-option
            v-for="dict in status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="审核状态" prop="dr">
        <el-select v-model="queryParams.dr" placeholder="请选择">
          <el-option
            v-for="dict in dict.type.audit_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['information:set:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['information:set:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['information:set:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="setList" @selection-change="handleSelectionChange" height="650" fixed>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="编号" align="center" prop="id"/>
      <el-table-column label="位置" align="center" prop="title">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.banner_type" :value="scope.row.title"/>
        </template>
      </el-table-column>
      <el-table-column label="图片" align="center" prop="images" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="createTime"/>
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <div v-for="item in status" v-if="item.value === scope.row.state">
            <span>{{ item.label }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="dr">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_status" :value="scope.row.dr"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.state===1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleState(scope.row)"
            v-hasPermi="['information:set:edit']"
          >上架
          </el-button>
          <el-button
            v-if="scope.row.state===0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleState(scope.row)"
            v-hasPermi="['information:set:edit']"
          >下架
          </el-button>
          <el-button
            style=""
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="spaceAudit(scope.row)"
            v-if="scope.row.dr===0"
            v-hasPermi="['information:set:process']"
          >审核
          </el-button>
          <el-button
            style=""
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="spaceAudit(scope.row)"
            v-if="scope.row.dr===3"
            v-hasPermi="['information:set:process2']"
          >审核
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['information:set:edit']"
          ><span v-if="$store.getters.userId===scope.row.sort">编辑</span>
            <span v-if="$store.getters.userId!==scope.row.sort">查看</span>
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDelete(scope.row)"
            v-hasPermi="['information:set:delete']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open2" width="1500px" :close-on-click-modal='false' append-to-body
               @opened="modalOpened"
               @close="closeDialog">
      <el-row>
        <el-col :xs="24" :md="24" :style="{marginLeft:'25px',width:'1400px',height: '600px'}">
          <vue-cropper
            ref="cropper"
            :img="form.images"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
            v-if="visible"
          />
        </el-col>
        <el-col :xs="24" :md="24" :style="{height: '600px'}">
          <div class="photo">
            <img :src="previews.url" :style="previews.img"/>
          </div>
        </el-col>
      </el-row>
      <br/>
      <el-row>
        <!--        <el-col :lg="2" :sm="3" :xs="3">-->
        <!--          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">-->
        <!--            <el-button size="small">-->
        <!--              选择-->
        <!--              <i class="el-icon-upload el-icon&#45;&#45;right"></i>-->
        <!--            </el-button>-->
        <!--          </el-upload>-->
        <!--        </el-col>-->
        <el-col :lg="{span: 1, offset: 2}" :sm="2" :xs="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :sm="2" :xs="2">
          <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 添加或修改V1.0配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal='false' width="800px" append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="位置" prop="title">
          <el-select v-model="form.title" placeholder="请选择标题">
            <el-option
              v-for="dict in dict.type.banner_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="图片" prop="images">
          <image-upload :limit="1" v-model="form.images"/>
        </el-form-item>
        <el-form-item label="审核备注" v-if="form.dr!==0" prop="content">
          <el-input disabled class="kind" type="textarea" v-model="form.content"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="$store.getters.userId===form.sort" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 审核 -->
    <el-dialog title="审核" :visible.sync="buildingAudit" close-on-click-modal center width="750px">
      <el-form :model="form" label-width="130px">
        <el-form-item label="审核备注" prop="content">
          <el-input class="kind" type="textarea" v-model="form.content"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="success" v-if="form.dr===0" @click="submitCheck(3)">审核通过</el-button>
        <el-button type="success" v-if="form.dr===3" @click="submitCheck(1)">审核通过</el-button>
        <span style="width: 5%;display: inline-block"></span>
        <el-button type="danger" v-if="form.dr===0" @click="submitCheck(2)">审核驳回</el-button>
        <el-button type="danger" v-if="form.dr===3" @click="submitCheck(4)">审核驳回</el-button>
        <span style="width: 5%;display: inline-block"></span>
        <el-button type="info" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addSet, delSet, getSet, listSet, updateSet, uploadBanner} from "@/api/information/set";
import store from "@/store";
import {VueCropper} from "vue-cropper";
import {debounce} from '@/utils'

export default {
  name: "Set",
  dicts: ['banner_type','audit_status'],
  components: {VueCropper},
  data() {
    return {
      open2: false,
      // 是否显示cropper
      visible: false,
      // 弹出层标题
      options: {
        img: store.getters.avatar, //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 1200, // 默认生成截图框宽度
        autoCropHeight: 480, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        outputType: "png" // 默认生成截图为PNG格式
      },
      previews: {},
      resizeHandler: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      buildingAudit: false,
      // 总条数
      total: 0,
      // V1.0配置表格数据
      setList: [],
      // 弹出层标题
      title: "",
      status: [
        {
          value: 0,
          label: "上架"
        }, {
          value: 1,
          label: "下架"
        },
      ],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        setType: 5,
        title: null,
        content: null,
        images: null,
        sort: null,
        state: null,
        dr: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          {required: true, message: "标题不能为空", trigger: "change"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    "form.images"() {
      if (!this.open2 && this.form.images != null && this.form.images != "" && this.form.setOop == 1) {
        this.open2 = true;
      }
      if (this.form.setOop == 0) {
        this.form.setOop = 1
      }
    }
  },
  methods: {
    /** 提交审核 */
    submitCheck(state) {
      updateSet({
        id: this.form.id,
        dr: state,
        content: this.form.content
      }).then(response => {
        this.$modal.msgSuccess("审核成功");
        this.buildingAudit = false;
        this.getList();
      });
    },
    /** 审核 */
    spaceAudit(row) {
      this.reset();
      this.form.id = row.id
      this.buildingAudit = true;
      this.form.content = row.content
      this.form.dr = row.dr
    },
    // 编辑头像
    editCropper() {
      this.open = true;
    },
    // 打开弹出层结束时的回调
    modalOpened() {
      this.open2 = true;
      this.visible = true;
      if (!this.resizeHandler) {
        this.resizeHandler = debounce(() => {
          this.refresh()
        }, 100)
      }
      window.addEventListener("resize", this.resizeHandler)
    },
    // 刷新组件
    refresh() {
      this.$refs.cropper.refresh();
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.form.images = reader.result;
        };
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData();
        formData.append("file", data);
        uploadBanner(formData).then(response => {
          // this.open2 = false;
          this.form.images = response.data.url;

          this.visible = false;
          // this.$emit("open2",false)
        }).finally(res => {
          this.open2 = false;
        });

      });
    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    // 关闭窗口
    closeDialog() {
      // this.options.img = this.form.images
      this.open2 = false
      this.visible = false;
      window.removeEventListener("resize", this.resizeHandler)
    },
    /** 启用禁用按钮操作 */
    handleState(row) {
      const id = row.id
      if (row.state === 0) {
        this.$modal.confirm('是否确认下架编号为"' + id + '"的数据项？').then(function () {
          row.state = 1
          return updateSet(row)
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("推荐成功");
        }).catch(() => {
        });
      } else {
        this.$modal.confirm('是否确认上架编号为"' + id + '"的数据项？').then(function () {
          row.state = 0
          return updateSet(row)
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("解除推荐成功");
        }).catch(() => {
        });
      }

    },
    /** 查询V1.0配置列表 */
    getList() {
      this.loading = true;
      listSet(this.queryParams).then(response => {
        this.setList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.buildingAudit = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        setType: null,
        title: null,
        content: null,
        images: null,
        sort: this.$store.getters.userId,
        state: null,
        dr: 0,
        createTime: null,
        updateTime: null,
        setOop: 1
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSet(id).then(response => {
        this.form = response.data;
        this.open = true;
        if (this.$store.getters.userId !== this.form.sort) {
          this.title = "广告详情";
        } else {
          this.title = "修改广告";
        }
        this.form.setOop = 0
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.dr = 0
            updateSet(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.setType = 5
            addSet(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除广告编号为"' + ids + '"的数据项？').then(function () {
        return delSet(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('information/set/export', {
        ...this.queryParams
      }, `set_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
.user-info-head {
  position: relative;
  display: inline-block;
  height: 120px;
}

.user-info-head:hover:after {
  content: '+';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 110px;
  border-radius: 50%;
}

.photo {
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 1200px;
  height: 480px;
  box-shadow: 0 0 4px #1945d8;
  overflow: hidden;
}

</style>
